package kz.edu.sdu.itech.qms;

import kz.edu.sdu.itech.qms.util.Logger;

public class Serve extends Thread implements Runnable {
   static final String INIT = "Not started";
   static final String SERVING = "Serving";
   static final String SLEEPING = "Sleeping";
   static final String FINISHED = "Finished";

   Logger log;
   Queue q;
   int time;
   String serveState = INIT;
   Client curClient = null;

   public Serve(Queue q) {
      log = new Logger(String.format("[%s: serve=%s]", Serve.class.getName(), q.getDid()));
      this.q = q;
   }

   @Override
   public void start() {
      log.debug("starting...");
      super.start();
   }

   @Override
   public void run() {
      while (!QMSProps.DONE) {
         try {
            if (q.size() > 0){
               serveState = SERVING;
               time = QMSProps.getServeTime();
               log.debug(String.format("%d: next client will be served in %d seconds", q.size(), time));
               curClient = q.pop();
               Thread.sleep(time * 1000);
               log.debug(String.format("%d: %s was served in %d seconds [%s]", q.size(), curClient.getClientName(), time, curClient.getClientTicket()));
            } else {
               serveState = SLEEPING;
//               log.debug("quee is empty. zzz...");
               Thread.sleep(1000);
            }
         } catch (InterruptedException e) {
            e.printStackTrace();
         } finally {
         }
      }
      serveState = FINISHED;
      log.debug(String.format("exiting. queue size is %d", q.size()));
   }

   public String getServeState() {
      return serveState;
   }

   public Client getCurClient() {
      return curClient;
   }

   public int getDID() {
      return q.getDid();
   }

}
